# -*- coding: utf-8 -*-

import json

from django.views.decorators.http import require_POST, require_GET
from common.system_recharge.db import create_system_trans, list_all_detail
from common.admin.db import get_nickname_by_id
from common.utils.tz import utc_to_local_str
from common.utils.decorator import response_wrapper
from common.utils.api import token_required
from common.utils.currency import convert_fen_to_yuan
from common.utils import exceptions as err


@require_GET
@response_wrapper
@token_required
def sys_recharge(req):
    query_dct = req.GET.dict()
    items, total_count = list_all_detail(query_dct)

    resp_items = []
    for item in items:
        data = item.as_dict()
        data.pop('batch_id')
        data['created_at'] = utc_to_local_str(data['created_at'])
        data['updated_at'] = utc_to_local_str(data['updated_at'])
        data['amount'] = convert_fen_to_yuan(data['amount'])
        resp_items.append(data)

    return {'list': resp_items, 'page': query_dct.get('$page', 1),
            'size': len(resp_items), 'total_count': total_count}


@require_POST
@response_wrapper
@token_required
def create_sys_recharge(req, trans_id):
    admin_id = req.user_id
    operator = get_nickname_by_id(admin_id)
    if not req.body:
        raise err.ParamError(u'参数错误')
    data = json.loads(req.body)
    params = data.get('detail_info', 0)
    note = data.get('note', 0)
    black_type = data.get('black_type', None)
    enable_withdraw = int(data.get('enable_withdraw', False))
    if enable_withdraw not in [0, 1]:
        raise err.ParamError(u'参数错误')
    create_system_trans(trans_id, params, operator, note, admin_id, black_type, enable_withdraw)

    return {}